$(document).ready(function () {


    /***等待图****/
    var opts = {
        lines: 9, // The number of lines to draw
        length: 0, // The length of each line
        width: 12, // The line thickness
        radius: 43, // The radius of the inner circle
        scale: 1.05, // Scales overall size of the spinner
        corners: 1, // Corner roundness (0..1)
        color: '#01CBE9', // CSS color or array of colors
        fadeColor: 'transparent', // CSS color or array of colors
        speed: 1, // Rounds per second
        rotate: 0, // The rotation offset
        animation: 'spinner-line-fade-quick', // The CSS animation name for the lines
        direction: 1, // 1: clockwise, -1: counterclockwise
        zIndex: 2e9, // The z-index (defaults to 2000000000)
        className: 'spinner', // The CSS class to assign to the spinner
        top: '34%', // Top position relative to parent
        left: '50%', // Left position relative to parent
        shadow: '0 0 1px transparent', // Box-shadow for the lines
        position: 'absolute' // Element positioning
    };

    var target = document.getElementById('spin');
    var spinner = new Spinner(opts).spin(target);


    //获取地址信息
    var Request = new searchUrl(),//地址参数化。方法来自base.js
        postId = Request.postId,   //帖子id
        from = Request.from,     //来源
        prisession = sessionStorage.getItem('pri'),   //点赞的id
        listCurrentPage = 1,      //评论数据起始页
        scorllNo = 0,
        fcid = '',
        pri = [],                  //点赞id数组
        msg = '',                  //提示容器
        userInfo = getUserInfo(),   //用户信息
        username = userInfo.name,
        productId = Request.productid,
        userComment = {};


    //创建帖子信息
    myAjaxFunc({
        url: community + "getPost",
        type: 'post',
        dataType: 'json',
        data: {id: postId},
        mySuccess: function (data) {
            if (isResponseSuccess('success', data)) {

                $('#spin').fadeOut();
                $('main').fadeIn();


                var item = data.data.item
                    , creatername = item.creater.name
                    , createrimgUrl = item.creater.imgUrl
                    , groupid = item.group.id
                    , groupName = item.group.name
                    , roles = item.creater.roles
                    , createTime = item.createTime
                    , textContent = item.textContent
                    , imgUrls = item.imgUrls
                    , thumbUp = item.thumbUp
                    , commentCount = item.commentCount
                    , textContentShort = item.textContentShort
                    , title = item.title
                    , imglist = '', imgList = ''
                    , imgUrl = item.creater.imgUrl;

                //面包屑导航
                $('#fromGroup').html(groupName).attr('href', 'groupItem.html?groupId=' + groupid);
                $('#navpostinfo').html(textContentShort).attr('href', 'groupPostDetail.html?postId=' + postId);
                //标题


                if (roles == '管理员') {
                    $('.postTitle').show()

                } else {
                    $('.postTitle').hide()
                }

                if (isNull(title)) {
                    $('#postTitle').hide();
                }

                $('#postTitle').html(title);

                //作者
                $('#writerName').html(creatername);
                $('#UserCenterInfoName').html(creatername);
                $('#UserCenterInfoImg').attr('src', geturlimg + createrimgUrl);

                $('#createTime').html('发表于 ' + createTime);

                $('#topzanNumber').html(thumbUp);

                var obj = new Object();

                obj.postid = postId;
                obj.thumbUpNumber = thumbUp;

                $('#zanNumber').html('赞' + thumbUp).addClass(postId).data(obj);

                if (thumbUp == 0) {
                    $('#zanNumber').html('赞').addClass(postId).data(obj);
                }


                $('#lookNumber').html(commentCount); //浏览信息
                $('#commentNumber').html(commentCount);

                //内容
                $('#postContent').html(textContent)

                productId = item.group.productId;
                sessionStorage.setItem('productId', productId);


                $('#publishTime').html(createTime);
                $('.praise i').html(thumbUp);
                $('.comment i').html(commentCount);
                $('#userImgTop').attr('src', geturlimg + imgUrl);

            } else {
                defaultHint('获取数据中断');
                window.history.back();
            }

        }
    });


    $('#zanNumber').click(function () {

        var this_ = $(this);

        var type = this_.hasClass("praiseTypePost");

        if (type) {

            if (this_.data('thumbUpNumber') > 0) {
                this_.removeClass('praiseTypePost');
                this_.html('赞' + Number(this_.data('thumbUpNumber')));
                var priid = this_.data('postid');
                myAjaxFunc({
                    url: community + 'thumbDownPost',
                    data: {id: priid}
                })
                removePri(priid)
            }

        } else {

            this_.addClass('praiseTypePost');
            this_.html('赞' + Number(this_.data('thumbUpNumber') + 1));
            var priid = $(this).data('postid');

            addPri(priid); //存储点赞id

            myAjaxFunc({
                url: community + 'thumbUpPost',
                data: {id: priid}
            })
        }

    });


    //去除登入阻挡
    if (islogin()) {
        $('#notLoginBox').hide();
    }




    $('#notLogin').click(function(){
        $('#loginMode').show();
    });


    //一级评论添加图片

    /*****一级评论添加图片****/
    var imgData = '', formData = new FormData();
    $('#postImg').change(function () {
        var _this = $(this)[0],
            _filelist = _this.files[0],
            fileType = _filelist.type;
        var blob = new Blob([_filelist], {type: fileType});
        var fileReader = new FileReader();
        fileReader.readAsDataURL(_filelist);
        fileReader.onload = function (event) {
            var result = event.target.result;   //返回的dataURL
            $('#commentImg').attr('src', result);
            formData.append('imgAttach', blob);
            imgData = imgUpFile(formData);
            $('.imgItem').show();
            $('.postImg').hide();
        };

    });

    $('#deleteImg').click(function () {
        imgData = '';
        $('.imgItem').hide();
        $('.postImg').show();

    });

    $('#postOne').click(function () {

        var userSendOneTxt = $('#userCommentOne').val();

        var srt = /script/g;
        userSendOneTxt = userSendOneTxt.replace(srt, "**");


        userSendOneTxt = userSendOneTxt.replace(/\ +/g, "");//去掉空格

        userSendOneTxt = userSendOneTxt.replace(/[ ]/g, ""); //去掉空格

        userSendOneTxt = userSendOneTxt.replace(/[\r\n]/g, "");//去掉回车换行


        var userinfo = getUserInfo();

        if (isNull(userinfo.name)) {
            defaultHint('您还没未设置昵称，请前往个人中心设置')
            return
        }

        if (isNull(userinfo.imgUrl)) {
            defaultHint('您还没未设置头像，请前往个人中心设置')
            return
        }

        if (isNull(userSendOneTxt)) {
            defaultHint('不能写空评论');
            return
        }

        if (userSendOneTxt.length > 120) {
            defaultHint('文字超过限制')
            return
        }

        /*****获取帖子的评论****/
        myAjaxFunc({
            url: community + "sendComment",
            type: 'post',
            dataType: 'json',
            // data: {postId: postId, textContent: userSendOneTxt, fatherCommentId: userComment.fatherCommentId},
            data: {postId: postId, textContent: userSendOneTxt},
            mySuccess: function (data) {

                if (isResponseSuccess('success', data)) {

                    defaultHint('评论成功');
                    $('#userCommentOne').val('');


                } else {
                    msg = isResponseSuccess('msg', data);
                    if (notNull(msg)) {
                        defaultHint(msg);
                    } else {
                        msg = '发送失败';
                        defaultHint(msg);
                    }
                }
            }
        })

    });







    //获取帖子的评论
    function getPageCommentfn(listCurrentPage) {
        myAjaxFunc({
            url: community + "getPageComment",
            type: 'post',
            dataType: 'json',
            data: {postId: postId, listCurrentPage: listCurrentPage},
            mySuccess: function (data) {
                console.log(data.data)
                if (isResponseSuccess('success', data)) {
                    let postData = isResponseSuccess('getdata', data);

                    postData.list.roles = set_roles();   //配置管理员信息

                    postData.list.listCurrentPage = postData.extra.listCurrentPage;  //配置当前页
                    postData.list.geturl = geturlimg;     //配置图片加载地址
                    let leng = postData.list.length;

                    if (leng < 0) {
                        return
                    }

                    //配置图片为数组

                    let pageInfo = postData.extra,
                        allpage = pageInfo.listPageCount, //总页数
                        atpage = pageInfo.listCurrentPage; //当前页数
                    creationPage(allpage, atpage);
                    var html = template('postDetail-post-list-template', postData);

                    $('#postCommentItem').empty().append(html);

                    // setTimeout(showPri(), 200);
                }

            }
        })
    }

    getPageCommentfn(1); //初始化第一页

    function creationPage(allpage, atpage) {

        Page({
            num: allpage,			//页码数
            startnum: atpage,		//指定页码
            elem: $('#page'),		//指定的元素
            callback: function (n) {	//回调函数
                getPageCommentfn(n);
            }
        });
    }

    //对一级评论进行评论，呼出评论输入框（产生二级评论）

    $('#postCommentItem').on('click', '.reply', function () {
        var this_ = $(this);
        var classname = this_.data('classname');

        $('.' + classname).show()

    }).on('click', '.btnPostCommentTwoClose', function () {

   //对一级评论进行评论，呼出评论输入框（产生二级评论），中途取消二级评论

        var this_ = $(this);

        this_.parent().hide()

    }).on('click', '.btnPostCommentTwo', function () {
        //对一级评论进行评论，呼出评论输入框（产生二级评论），发送二级评论

        var this_ = $(this);
        var thisid = this_.data('thisid');


        var userSendTwoTxt = this_.parent().find('.postCommentTwoSendBox').val();

        var srt = /script/g;

        userSendTwoTxt = userSendTwoTxt.replace(srt, "**");

        userSendTwoTxt = userSendTwoTxt.replace(/\ +/g, "");//去掉空格

        userSendTwoTxt = userSendTwoTxt.replace(/[ ]/g, ""); //去掉空格

        userSendTwoTxt = userSendTwoTxt.replace(/[\r\n]/g, "");//去掉回车换行


        var userinfo = getUserInfo();

        if (isNull(userinfo.name)) {
            defaultHint('您还没未设置昵称，请前往个人中心设置');
            return
        }

        if (isNull(userinfo.imgUrl)) {
            defaultHint('您还没未设置头像，请前往个人中心设置');
            return
        }

        if (isNull(userSendTwoTxt)) {
            defaultHint('不能写空评论');
            return
        }

        if (userSendTwoTxt.length > 120) {
            defaultHint('文字超过限制')
            return
        }

        /*****获取帖子的评论****/
        myAjaxFunc({
            url: community + "sendComment",
            type: 'post',
            dataType: 'json',
            data: {postId: postId, textContent: userSendTwoTxt, fatherCommentId: thisid},
            mySuccess: function (data) {

                if (isResponseSuccess('success', data)) {

                    defaultHint('评论成功');
                    $('#userCommentOne').val('');
                    this_.parent().hide()

                } else {
                    msg = isResponseSuccess('msg', data);
                    if (notNull(msg)) {
                        defaultHint(msg);
                    } else {
                        msg = '发送失败';
                        defaultHint(msg);
                    }
                }
            }
        })


    })


});

















